/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.io.IOException;
import java.sql.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author Eduardo
 */
public class Login extends HttpServlet {

    public Statement conn() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/delc", "root", "password");
        Statement stmt = conn.createStatement();
        return stmt;
    }

    public String createHash(String plainText) throws NoSuchAlgorithmException {
        MessageDigest mdAlgorithm = MessageDigest.getInstance("SHA1");
        mdAlgorithm.update(plainText.getBytes());
        byte[] digest = mdAlgorithm.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            plainText = Integer.toHexString(0xFF & digest[i]);
            if (plainText.length() < 2) {
                plainText = "0" + plainText;
            }
            hexString.append(plainText);
        }
        return hexString.toString();
    }

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {
        HttpSession session = request.getSession(true);
        if (request.getParameter("username") == null || request.getParameter("password") == null) {
            return;
        }
        String login = request.getParameter("username");
        String pass = request.getParameter("password");
        String senha = null;
        try {
            senha = createHash(pass);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        String query = "select p.nome, p.siape, p.password, p.email, p.id, d.diretor_id FROM professores p LEFT JOIN departamentos d ON d.id = p.departamento_id  = p.departamento_id where siape = '" + login + "' LIMIT 1";
        ResultSet rs = null;
        try {
            rs = conn().executeQuery(query);
        } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            if (rs.next()) {
                if (rs.getString("password").equals(senha)) {
                    session.setAttribute("nome", rs.getString("nome"));
                    session.setAttribute("email", rs.getString("email"));
                    session.setAttribute("id", rs.getInt("id"));
                    Integer pid = rs.getInt("id");
                    session.setAttribute("talogado", "true");

                    String query2 = "select curso_id, nome, cordenador_id FROM cursos WHERE cordenador_id = '" + pid + "'";
                    ResultSet rs2 = null;
                    try {
                        rs2 = conn().executeQuery(query2);
                    } catch (SQLException | ClassNotFoundException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (rs2 != null && rs2.next()) {
                        session.setAttribute("type", "cordenador");
                        session.setAttribute("curso_id", rs2.getInt("curso_id"));
                        session.setAttribute("curso_nome", rs2.getString("nome"));

                    } else if (rs.getInt("diretor_id") == rs.getInt("id")) {
                        session.setAttribute("type", "diretor");
                    } else {
                        session.setAttribute("type", "professor");

                    }
                    response.sendRedirect("home.jsp");
                } else {
                    session.setAttribute("error", "Login ou senha inválidos.");
                    response.sendRedirect("login.jsp");
                }
            } else {
                session.setAttribute("error", "Login ou senha inválidos.");
                response.sendRedirect("login.jsp");
            }
        } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
